<?php
/**
 * @Created by PhpStorm.
 * @Name 订单控制器
 * @User: Wong
 * @Date: 2016/10/28
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace admin\action;

use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\filter\Filter;
use herosphp\core\Loader;
use api\utils\PayApiClient;

/**--tmpl-use--**/

class OrderAction extends CommonAction {

	public function C_start()
	{
		parent::C_start();
	}

	protected $serviceBean="trading.tradingOrder.service";

    /**
     * 订单详情
     * @param HttpRequest $request
     */
    public function detail(HttpRequest $request){
        $orderService = Beans::get($this->getServiceBean());
        $OrderModel = Loader::model('tradingOrder');
        $id = $request->getParameter('id');
        $no = $request->getParameter('no');
        $remake = $request->getParameter('sellers_remark');
        $type = $request->getParameter('type');
        if($type == 1){//更新卖家备注
            if($orderService->updates(array('sellers_remark'=>$remake),array('id'=>$id,'app_id'=>appId()))){
                AjaxResult::ajaxSuccessResult();
            }else{
                AjaxResult::ajaxFailtureResult();
            }
        }
        $item = $orderService->getDetail($id,$no);
        if(!$item){
            return $this->showMessage(1,'没有此订单','/admin/order/index');
        }
        if($item == 'denied'){
            return $this->message(1,'您无权限查看此订单','/admin/order/index');
        }
        $item['payway'] = $orderService->getPaywayText($item['pay_way']);
        $item['shippingway'] = $orderService->getShippingwayText($item['shipping_way']);
        $item['step'] = $item['order_status']>=3?$item['order_status']-3:0;

        $this->assign('item',$item);
        $this->assign('PAY_WAY_OFFLINE', $OrderModel::PAY_WAY_OFFLINE);
        $this->assign('ORDER_STATUS_UNPAY', $OrderModel::ORDER_STATUS_UNPAY);
        $this->assign('ORDER_PENDING_RECEIPT', $OrderModel::ORDER_PENDING_RECEIPT);
        $this->assign('ORDER_STATUS_TO_BE_SHIPPED', $OrderModel::ORDER_STATUS_TO_BE_SHIPPED);
        $this->assign('ORDER_STATUS_SHIPPED', $OrderModel::ORDER_STATUS_SHIPPED);
        $this->assign('ORDER_STATUS_COMPLETED', $OrderModel::ORDER_STATUS_COMPLETED);
        $this->assign('ORDER_STATUS_CANCELED', $OrderModel::ORDER_STATUS_CANCELED);
        $this->assign('SHIPPING_WAY_SELLER', $OrderModel::SHIPPING_WAY_SELLER);
        $this->assign('SHIPPING_WAY_BUYER', $OrderModel::SHIPPING_WAY_BUYER);

        $this->assign("title", "订单详情");
        $this->assign('bread', array('交易管理','订单列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/order/index'),'javascript:;'));
        $this->setView(strtolower($request->getAction()).'/detail');
    }

    /**
     * 添加订单页面
     * @param HttpRequest $request
     */
	public function add(HttpRequest $request) {

		$this->assign("title", "添加订单");
		$this->assign('bread', array('交易管理',$this->getTemplateVar('title')));
		$this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()).'/add');
    }

    /**
     * 编辑订单页面
     * @param HttpRequest $request
     */
	public function edit(HttpRequest $request) {

        $addressService = Beans::get('member.receiptAddress.service');
        $orderModel = Loader::model('tradingOrder');
        $id = $request->getParameter('id');
        if ( $id == '' ) {
            $this->showMessage('danger', COM_ERR_MSG);
        } else {

            $service = Beans::get($this->getServiceBean());
            $item = $service->getDetail($id);
            if(!$item){
                return $this->showMessage(1,'没有此订单','/admin/order/index');
            }
            if($item == 'denied'){
                return $this->message(1,'您无权限查看此订单','/admin/order/index');
            }

        }

        $address_item = $addressService->getAddress(array('member_id'=>$item['member_id']));

		$this->assign("title", "订单编辑");
		$this->assign('bread', array('交易管理','订单列表',$this->getTemplateVar('title')));
		$this->assign('breadUrl', array('javascript:;',url('admin/order/index'),'javascript:;'));
        $this->assign('id',$id);
        $this->assign('item', $item);
        $this->assign('DIRECTRADE', $orderModel::DIRECTRADE);//直接交易模式
        $this->assign('WAIT_FOR_MERCHANT_CONFIRMATION', $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION);//待卖家确认
        $this->assign('ADD_TYPE_SELLER', $orderModel::ADD_TYPE_SELLER);//运营商添加的
        $this->assign('PAY_WAY_OFFLINE', $orderModel::PAY_WAY_OFFLINE);
        $this->assign('SHIPPING_WAY_SELLER', $orderModel::SHIPPING_WAY_SELLER);
        $this->assign('SHIPPING_WAY_BUYER', $orderModel::SHIPPING_WAY_BUYER);
        $this->assign('address_item', $address_item);
        $this->setView(strtolower($request->getAction()).'/add');
	}

    /**
     * 订单列表
     * @param HttpRequest $request
     */
	public function index(HttpRequest $request) {
        $orderService = Beans::get($this->getServiceBean());
        $orderModel = Loader::model('tradingOrder');
        $s_order_no = $request->getParameter('s_order_no');
        $s_consignee_type = $request->getParameter('s_consignee_type');
        $s_consignee = $request->getParameter('s_consignee');
        $s_consignee = urldecode($s_consignee);
        $s_contact_type = $request->getParameter('s_contact_type');
        $s_contact_mobile = $request->getParameter('s_contact_mobile');
        $s_order_status = $request->getParameter('s_order_status');
        $s_time_type = $request->getParameter('s_time_type');
        $s_s_order_time = $request->getParameter('s_s_order_time');
        $s_e_order_time = $request->getParameter('s_e_order_time');
        $pagesize = $request->getParameter('pagesize') ? $request->getParameter('pagesize') : $this->getPagesize();
        $this->setPagesize($pagesize);
        $page = $request->getParameter('page');
        $page = $page>0?$page:1;
        $this->setPage($page);

        $conditions = array();
		$conditions['order_no'] = $s_order_no;
        if($s_consignee != ''){
            if($s_consignee_type == 1){//提货人
                $conditions['shipping_fullname'] = $s_consignee;
                if($s_contact_type == 1){
                    $conditions['shipping_mobile'] = $s_contact_mobile;
                }
            }else{
                $conditions['consignee'] = $s_consignee;
                if($s_contact_type != 1){
                    $conditions['contact_mobile'] = $s_contact_mobile;
                }
            }
        }else{
            if($s_contact_type == 1){
                $conditions['shipping_mobile'] = $s_contact_mobile;
            }else{
                $conditions['contact_mobile'] = $s_contact_mobile;
            }
        }

		if($s_time_type == 1){
            if($s_s_order_time != ''){
                $conditions['pay_s_time'] = $s_s_order_time;
            }
            if($s_e_order_time != ''){
                $conditions['pay_e_time'] = $s_e_order_time;
            }
        }else{
            if($s_s_order_time != ''){
                $conditions['order_s_time'] = $s_s_order_time;
            }
            if($s_e_order_time != ''){
                $conditions['order_e_time'] = $s_e_order_time;
            }
        }

		if($s_order_status !== '' && $s_order_status!== NULL)$conditions['order_status'] = $s_order_status;

        //选择导出
        if( $request -> getParameter('export') ==1 ){
            $ids = $request -> getParameter('ids');

            if( $ids ){
                $tmp = "('0'";
                foreach ($ids as $value){
                    $tmp .= ','."'$value'";
                }
                $conditions['id']=$tmp.')';
            }
            $page = 1;
            $pagesize = 2147483648;
        }

        $items = $orderService->getOrderList($conditions,$pagesize,$page);
        $this->generatePageMenu($items['total']);

        $option_arr = array(/*'0'=>'待用户议价',*/'1'=>'待卖家确认','2'=>'待买家确认','3'=>'待支付',/*'4'=>'待确认收款',*/'5'=>'待发货','6'=>'已发货','7'=>'已完成','8'=>'已取消');

        $items = $items['items'];
        foreach ($items as $k => $item) {

            $items[$k]['payway'] = $orderService->getPaywayText($item['pay_way']);
            $items[$k]['shippingway'] = $orderService->getShippingwayText($item['shipping_way']);
            $items[$k]['orderstatus'] = $orderService->getPaystatusText($item['order_status']);

        }
        if( $request->getParameter('export') == 1){
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["order_no"];
                $tmp[] = $v["amount"];
                $tmp[] = $v["actual_amount"];
                $tmp[] = $v["payway"];
                $tmp[] = $v["shippingway"].($v['shipping_way']==$orderModel::SHIPPING_WAY_SELLER?"(收货人:".$v['consignee']." 收货人电话:".$v['contact_mobile'].')':"(提货人:".$v['shipping_fullname']." 提货人电话:".$v['shipping_mobile'].')');
                $tmp[] = $v["order_time"];
                $tmp[] = $v["orderstatus"];
                $excel[] = $tmp;
            }
            $header = array('订单号','总金额','应付金额','支付方式','配送方式','下单时间','订单状态');
            phpexcel("订单列表",$header,$excel);
            exit();
        }

        $this->assign('option_arr',$option_arr);
        $this->assign('_table','订单');
        $this->assign('s_order_no',$s_order_no);
        $this->assign('s_consignee',$s_consignee);
        $this->assign('s_consignee_type',$s_consignee_type);
        $this->assign('s_contact_mobile',$s_contact_mobile);
        $this->assign('s_contact_type',$s_contact_type);
        $this->assign('s_s_order_time',$s_s_order_time);
        $this->assign('s_e_order_time',$s_e_order_time);
        $this->assign('s_time_type',$s_time_type);
        $this->assign('s_order_status',$s_order_status);
        //交易模式
        $order_mode = C('order_mode');
		$this->assign('order_mode',$order_mode);
		$this->assign('pagesize',$pagesize);

        $this->assign('items', $items);
        $this->assign('SHIPPING_WAY_BUYER', $orderModel::SHIPPING_WAY_BUYER);
        $this->assign('PAY_WAY_OFFLINE', $orderModel::PAY_WAY_OFFLINE);
        $this->assign('WAIT_FOR_MERCHANT_CONFIRMATION', $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION);
        $this->assign('WAIT_FOR_USER_CONFIRMATION', $orderModel::WAIT_FOR_USER_CONFIRMATION);
        $this->assign('ORDER_STATUS_UNPAY', $orderModel::ORDER_STATUS_UNPAY);
        $this->assign('ORDER_PENDING_RECEIPT', $orderModel::ORDER_PENDING_RECEIPT);
        $this->assign('ORDER_STATUS_TO_BE_SHIPPED', $orderModel::ORDER_STATUS_TO_BE_SHIPPED);
        $this->assign('ORDER_STATUS_SHIPPED', $orderModel::ORDER_STATUS_SHIPPED);
        $this->assign('ORDER_STATUS_COMPLETED', $orderModel::ORDER_STATUS_COMPLETED);
        $this->assign('ORDER_STATUS_CANCELED', $orderModel::ORDER_STATUS_CANCELED);

		$this->assign("title", "订单列表");
		$this->assign('bread', array('交易管理',$this->getTemplateVar('title')));
		$this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/index');
    }

    /**
     * 生成订单
     * @param HttpRequest $request
     */
	public function do_add(HttpRequest $request){
        $orderModel = Loader::model('tradingOrder');
		$data = $request->getParameter('data');
		$data['shipping'] = $request->getParameter('shipping');
        $data['add_type'] = $orderModel::ADD_TYPE_SELLER;//运营商添加的订单
        $data['member_id'] = $request->getParameter('member_id');
        if(!$data['member_id']){
            AjaxResult::ajaxResult('001','订单没有选择会员');
        }
        $data['address']['id'] = $request->getParameter('address_id');
        if($data['shipping_way']==$orderModel::SHIPPING_WAY_SELLER && !$data['address']['id']){
            AjaxResult::ajaxResult('001','订单没有选择收货地址');
        }
        if($data['shipping_way']==$orderModel::SHIPPING_WAY_BUYER && $data['shipping']['shipping_fullname']==''){
            AjaxResult::ajaxResult('001','订单没有填写用户自提信息');
        }
		$product_data = $request->getParameter('product');
        if(!$product_data){
            AjaxResult::ajaxResult('001','订单没有选择产品');
        }
        foreach($product_data['product_quantity'] as $v){
            if($v<0){
                AjaxResult::ajaxResult('001','购买数量必须大于0',$v);
            }
        }

        foreach($product_data['product_actual_price'] as $v){
            if($v<0){
                AjaxResult::ajaxResult('001','金额必须大于0',$v);
            }
        }
        $data['product'] = $product_data;

        $orderService = Beans::get('trading.tradingOrder.service');
        $product_data = $orderService->addOrder($data);
        if($product_data == -1){
            AjaxResult::ajaxResult('001','订单没有选择产品');
        }elseif($product_data == -2){
            AjaxResult::ajaxResult('001','超出库存');
        }elseif($product_data == false){
            AjaxResult::ajaxResult('001','生成订单失败');
        }else{
            AjaxResult::ajaxSuccessResult();
        }
	}

    /**
     * 编辑订单
     * @param HttpRequest $request
     */
	public function do_edit(HttpRequest $request){
        $data = $request->getParameter('data');
        $id = $request->getParameter('id');
        $data['shipping'] = $request->getParameter('shipping');
        $data['member_id'] = $request->getParameter('member_id');
        if(!$data['member_id']){
            AjaxResult::ajaxResult('001','订单没有会员数据');
        }
        $data['address']['id'] = $request->getParameter('address_id');
        if(!$data['address']['id']){
            //AjaxResult::ajaxResult('001','订单没有选择收货地址');
        }
        $product_data = $request->getParameter('product');
        if(!$product_data){
            AjaxResult::ajaxResult('001','订单没有选择产品');
        }
        foreach($product_data['product_actual_price'] as $v){
            if($v<0){
                AjaxResult::ajaxResult('001','金额必须大于0',$v);
            }
        }
        $data['product'] = $product_data;

        $orderService = Beans::get('trading.tradingOrder.service');
        $product_data = $orderService->editOrder($data,$id);

        if($product_data == '-1'){
            AjaxResult::ajaxResult('001','订单没有选择产品');
        }elseif($product_data == '-3'){
            AjaxResult::ajaxResult('001','没有此订单');
        }elseif($product_data == false){
            AjaxResult::ajaxResult('001','生成订单失败');
        }else{
            AjaxResult::ajaxSuccessResult();
        }
	}

    /**
     * 手机号搜索会员收货地址
     * @param HttpRequest $request
     */
	public function searchMember(HttpRequest $request){
	    $phone_no = $request->getParameter('phone_no');
        $addressService = Beans::get('member.receiptAddress.service');
        if($phone_no==''){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'没有此用户');
        }
        $data = $addressService->getAddress(array('s_phone_no'=>$phone_no));
        if($data == -1){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'没有此用户');

        }else{
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',$data);
        }
	}

    /**
     * 运营商添加收货地址（用户看不到此收货地址）
     * @param HttpRequest $request
     */
    public function addAddress(HttpRequest $request){
        $addressService = Beans::get('member.receiptAddress.service');
        $data = array();
        $data['prov'] = $request -> getParameter('province');
        $data['city'] = $request -> getParameter('city');
        $data['dist'] = $request -> getParameter('dist');
        $data['address'] = $request -> getParameter('address');
        $data['detail_address'] = $request -> getParameter('detail').$data['address'];
        $data['consignee'] = $request->getParameter('consignee');
        $data['zip_code'] = $request->getParameter('zip_code');
        $data['contact_mobile'] = $request->getParameter('contact_mobile');
        $data['telephone'] = $request->getParameter('telephone');
        $data['member_id'] = $request->getParameter('member_id');
        $data['add_type'] = 1;
        $checkModel = array(
            'contact_mobile' => array(Filter::DFILTER_MOBILE, NULL, NULL,
                array("type" => "请输入正确的手机号码")),
        );

        $data = Filter::loadFromModel($data,$checkModel,$error);
        //var_dump($data);die;
        $res = $addressService->addAddress($data,1);//需要返回添加的数据信息
        if($res){
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',$res);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'添加失败');
    }

    /**
     * 货号搜索产品信息
     * @param HttpRequest $request
     */
	public function searchProduct(HttpRequest $request){
	    $key = $request->getParameter('product_no');
	    $member_id = $request->getParameter('member_id');
        $service = Beans::get('product.product.service');
        $data = $service->getProducts($key,$member_id);
        if($data){
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',$data);
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }


    /**
     * 运营商确认（不修改订单信息，只修改确认状态）
     * @param HttpRequest $request
     */
    public function merchantConfirmation(HttpRequest $request){
        $id = $request->getParameter('id');
        $service = Beans::get($this->getServiceBean());
        $item = $service->merchantConfirmation($id);
        if($item){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 银行账单流水
     * @param HttpRequest $request
     */
    public function billRecords(HttpRequest $request){
        $oppo_name = $request->getParameter('oppo_name');

        //获取运营商大塑支付id
        $api_data['appid'] = appId();
        $url = "api/user/getUserByAppId";

        $result = PayApiClient::send($url, $api_data);
        if ($result->isSucess()){
            $app_res = $result->getItem();
            $userId = $app_res['userid'];
        }else{
            Log::info($result->getMessage());
            exit('没有获取到运营商支付id');
        }
        //todo 调取大塑支付资金流水API
        $params['userid'] = $userId;
        if($oppo_name) $params['conditions'] = array('oppo_name'=>$oppo_name);
        $url = "api/order/getFundFlows";
        $result = PayApiClient::send($url, $params);
        if($result->isSucess()){
            $items = $result->getItems();

        }else{
            Log::info($result->getMessage());
            $items = array();
        }

        foreach($items as $k=>$v){
            $residual_amount = bcsub($v['amount'],$v['confirmed_money'],2);
            if($residual_amount<=0){
                unset($items[$k]);
                continue;
            }
            $items[$k]['residual_amount'] = $residual_amount;
        }

        $this->assign('items', $items);
        $this->assign('oppo_name', $oppo_name);
        $this->setView(strtolower($request->getAction()).'/billRecords');

    }

    /**
     * 确认收款
     * @param HttpRequest $request
     */
    public function confirmOrderPay(HttpRequest $request){
        $order_id = $request->getParameter('order_id');
        $id = $request->getParameter('id');
        $service = Beans::get($this->getServiceBean());
        $ids = explode(',',$id);
        $result = $service->confirmOrderPay($order_id,$ids);
        if($result==1){
            AjaxResult::ajaxSuccessResult();
        }elseif(!$result){
            AjaxResult::ajaxFailtureResult();
        }else{
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,$result);
        }

    }

    /**
     * 发货
     * @param HttpRequest $request
     */
    public function delivery(HttpRequest $request){
        $id = $request->getParameter('id');
        $data = $request->getParameter('data');

        $service = Beans::get($this->getServiceBean());
        $result = $service->delivery($id,$data);
        if($result){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 取消订单
     * @param HttpRequest $request
     */
    public function cancelOrder(HttpRequest $request){
        $id = $request->getParameter('id');
        $service = Beans::get($this->getServiceBean());
        $item = $service->cancelOrder($id);
        if($item){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

}
